package cn.jinjimi.app.modules.Resource;

import android.os.Build;
import android.webkit.WebResourceResponse;

import com.tencent.bugly.crashreport.CrashReport;
import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.FileUtils;
import cn.jinjimi.base.util.GsonUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.AppContext;
import cn.jinjimi.domain.data.dto.ResourceMapDTO;
import cn.jinjimi.app.entity.ResourceMap;
import cn.jinjimi.app.bean.SharePrefKeys;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by lforxeverc on 2017/7/31.
 */

class BundleHelper {
    private String resourceSubDirName;
    private static final String ResourceCacheFileName = "RecourceCache";
    private static final String ResourceZipCacheFileName = "RecourceZipCache";
    private static final String ResourceMapJsonName = "map.json";
    public final int OUTLINE_RESOURCE_TYPE = 0;
    public static final int REACT_NATIVE_RESOURCE_TYPE = 1;

    private final Resource.Bundle mBundle;
    private boolean mIsValid;

    private String mCacheMd5;
    private Map<String, ResourceMap> netResourceMap = new HashMap<>();

    // 下载的压缩文件存储地址
    private String fileZipsPath = FileUtils.getAppCache(AppContext.getInstance(), ResourceZipCacheFileName);
    // 解压后的资源文件存放地址
    private static String FileResourcePath = FileUtils.getAppCache(AppContext.getInstance(), ResourceCacheFileName);

    public BundleHelper(Resource.Bundle mBundle) {
        this.mBundle = mBundle;
        this.mIsValid = mBundle != null && mBundle.isValid() && mBundle.type == OUTLINE_RESOURCE_TYPE;
        if (mIsValid) {
            mCacheMd5 = PreferenceManager.getStringData(getMd5Key());
        }
    }

    private String getMd5Key() {
        return mIsValid ? (SharePrefKeys.PREF_NET_RESCOURCE_MD5 + mBundle.id) : "";
    }

    public String getId() {
        return mIsValid ? mBundle.id : "";
    }

    public String getEntranceUrl() {
        return mIsValid ? mBundle.entranceUrl : "";
    }

    public void init() {
        if (mIsValid) {
            if (!mBundle.md5.equals(mCacheMd5) || FileUtils.checkFileisEmpty(getResourcePath())) {
                downloadZip();
            } else {
                analysisResource();
            }
        }
    }

    /**
     * 判断是否含有此url的资源
     *
     * @param url
     * @return
     */
    public boolean containResource(String url) {
        return netResourceMap.containsKey(url);
    }

    /**
     * 根据url返回本地资源
     *
     * @param url
     * @return
     */
    public WebResourceResponse createWebResourceResponse(String url) {
        ResourceMap resourceMap = netResourceMap.get(url);
        try {
            String path = getResourcePath() + getResourceFileName() + File.separator + resourceMap.route;
            WebResourceResponse response = new WebResourceResponse(resourceMap.type, "UTF-8",
                    new FileInputStream(new File(path)));

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Access-Control-Allow-Origin", "*");
                headers.put("Access-Control-Allow-Methods", "GET");
                response.setResponseHeaders(headers);
            }

            return response;

        } catch (FileNotFoundException e) {
            //e.printStackTrace();
        }
        return null;
    }

    private void downloadZip() {
        //TODO
    }

    /* 解析map文件 */
    private void analysisResource() {
        try {
            ResourceMapDTO resourceMapDTO = GsonUtils.fromJson(FileUtils.getFileString(getResourcePath() + getResourceFileName() + File.separator + ResourceMapJsonName), ResourceMapDTO.class);
            if (resourceMapDTO != null
                    && resourceMapDTO.resourceMaps != null) {
                for (ResourceMap resourceMap : resourceMapDTO.resourceMaps) {
                    netResourceMap.put(resourceMap.url, resourceMap);
                }
            }
        } catch (Exception e) {
            CrashReport.postCatchedException(e);
        }
    }

    private String getResourcePath() {
        return FileResourcePath + mBundle.id + File.separator;
    }

    private String getResourceFileName() {
        if (StringUtils.isEmpty(resourceSubDirName)) {

            File file = new File(getResourcePath());
            if (file.exists()) {
                String[] names = file.list();
                if (names != null && names.length > 0) {
                    resourceSubDirName = names[0];
                }
            }
        }
        return resourceSubDirName;
    }

    private String getZipName() {
        return fileZipsPath + mBundle.id + ".zip";
    }

    public static void clearUselessFiles(final Set<String> bundleIds) {
        if (bundleIds != null && !bundleIds.isEmpty()) {
            File f = new File(FileResourcePath);
            if (f.exists()) {
                File[] uselessFiles = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String filename) {
                        return !bundleIds.contains(filename);
                    }
                });

                if (uselessFiles != null && uselessFiles.length > 0) {
                    for (File temp : uselessFiles) {
                        FileUtils.deleteDirectory(temp.getAbsolutePath());
                    }
                }
            }
        }
    }
}
